package com.zhengqiangblog.blog.dao.common;

import org.apache.log4j.Logger;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.zhengqiangblog.core.PropertiesHelper;

public class DataSourceFactory {

	private static final Logger logger = Logger.getLogger(DataSourceFactory.class);

	private final static String DRIVER_CLASS = "com.mysql.jdbc.Driver";
	private final static String JDBC_URL = "jdbc:mysql://127.0.0.1:3306/zq_blog?useUnicode=true&characterEncoding=utf8";
	private final static String USER = PropertiesHelper.get("mysql.user").toString();
	private final static String PASSWORD = PropertiesHelper.get("mysql.password").toString();

	private static ComboPooledDataSource dataSource = null;

	private static void initDataSource() throws Exception {
		dataSource = new ComboPooledDataSource();
		dataSource.setDriverClass(DRIVER_CLASS);
		dataSource.setJdbcUrl(JDBC_URL);
		dataSource.setUser(USER);
		dataSource.setPassword(PASSWORD);
		dataSource.setMaxIdleTime(3 * 60 * 60); // 3 hours
		dataSource.setMaxConnectionAge(6 * 60 * 60); // 6 hours
		dataSource.setInitialPoolSize(1);
		dataSource.setMinPoolSize(3);
		dataSource.setAcquireIncrement(3);
		dataSource.setMaxPoolSize(20);
	}

	public static ComboPooledDataSource getDataSource() {
		if (dataSource != null) {
			return dataSource;
		}
		synchronized (DataSourceFactory.class) {
			if (dataSource == null) {
				try {
					initDataSource();
				} catch (Exception e) {
					logger.error(e.getMessage(), e);
				}
			}
		}
		return dataSource;
	}

	public static void close() {
		dataSource.close();
	}

}
